package org.firebug.spring.boot.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 隐藏部分手机号码：12312341234 -> 123 **** 1234
 * @Author: 张晓东
 */
public class MobileHiddenSerializer extends JsonSerializer<String> {
    private static final String REGEX = "^1[0-9]{10}$";

    @Override
    public void serialize(String mobile, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        Matcher matcher = Pattern.compile("[0-9]+").matcher(mobile);
        String value = "";
        while (matcher.find()) {
            value += matcher.group();
        }
        if (value.matches(REGEX)) {
            value = value.substring(0, 3) + " **** " + value.substring(7);
        }
        gen.writeString(value);
    }
}
